package com.googlecode.maratische.google.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

import com.googlecode.maratische.google.BaseException;
import com.googlecode.maratische.google.DaoAction;
import com.googlecode.maratische.google.MainController;
import com.googlecode.maratische.google.utils.StringUtils;

public class CommandUpdateItemMedia extends Command {
	static Logger logger = Logger.getLogger(CommandUpdateItemMedia.class.getName());

	@Override
	public String getType() {
		return Commands.UpdateItemMedia.toString();
	}

	@Override
	public Integer getPriority() {
		return 5;
	}

	protected String getLocalMediaFileName(DaoAction daoAction,String fileName, String itemId) {
		String result = daoAction.getItemDao().getLocalMediaFolder(itemId);
		new File(result).mkdirs();
		result += File.separator+fileName;
		return result;
	}

	public boolean execute(DaoAction daoAction) throws SQLException, BaseException {
		int status = 0;
		String url = getString2();
		Item item = daoAction.getItemDao().get(new Integer(getString1()));
		if (url.indexOf("http://feeds.feedburner.com/~ff")>-1) {
			//http://feeds.feedburner.com/~ff/oper_ru?i=1pYITAlWYo8:GAGCnD3psBY:D7DqB2pKExk
		    item.setDescription(StringUtils.replace(item.getDescription(), url, ""));
		    daoAction.getItemDao().save(item);
		} else
		try {
			HttpClient httpClient = new HttpClient();
			GetMethod getMethod = new GetMethod(url);
//			String name = url.substring(url.lastIndexOf("/")+1);
			String name = "r";
			status = httpClient.executeMethod(getMethod);
			if (status == 200) {
				InputStream inputStream = getMethod.getResponseBodyAsStream();
				String fileName = null;
				Integer suffix = 0;
				do {
					fileName = getLocalMediaFileName(daoAction,(""+ suffix++)+name,getString1());
				} while (new File(fileName).exists());
				FileOutputStream fos = new FileOutputStream(fileName);
				byte buf[]=new byte[1024];
			    int len;
			    while((len=inputStream.read(buf))>0) {
			    	fos.write(buf,0,len);
			    }
			    fos.close();
			    inputStream.close();
			    //change urls
			    String description = item.getDescription();
			    description = StringUtils.replace(description, url, new File(fileName).toURI().toString());
			    item.setDescription(description);
			    daoAction.getItemDao().save(item);
			}
		} catch (IllegalStateException e) {
			if (e.getMessage() != null && e.getMessage().indexOf("unsupported protocol")==0) {
				MainController.getMainController().showError("Ошибка при скачивании медиаконтента (команда удалена)", e);
				daoAction.getCommandDao().remove(this);
			} else {
				throw e;
			}
		} catch (HttpException e) {
			throw new BaseException(e.getMessage());
		} catch (IOException e) {
			throw new BaseException(e.getMessage());
		}
		return true;
	}

}
